package com.yeskery.nut.view.thymeleaf;

import com.yeskery.nut.view.AbstractViewResolver;
import com.yeskery.nut.view.View;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * Thymeleaf视图解析器
 * @author sprout
 * 2022-07-07 14:45
 */
public class ThymeleafViewResolver extends AbstractViewResolver {

    /** 默认后缀名 */
    private static final String POSTFIX = "html";

    /** 模板引擎 */
    private final TemplateEngine templateEngine;

    /**
     * 构建Thymeleaf视图解析器
     */
    public ThymeleafViewResolver() {
        super(POSTFIX);
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(this.getClass().getClassLoader());
        templateResolver.setCacheTTLMs(3600000L);
        templateResolver.setCacheable(true);
        templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
    }

    /**
     * 构建Thymeleaf视图解析器
     * @param templateResolver 模板解析器
     */
    public ThymeleafViewResolver(ITemplateResolver templateResolver) {
        super(POSTFIX);
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
    }

    @Override
    public View createView(String viewName, Locale locale) throws Exception {
        return new ThymeleafView(templateEngine, viewName);
    }

    /**
     * 获取模板引擎
     * @return 模板引擎
     */
    public TemplateEngine getTemplateEngine() {
        return templateEngine;
    }
}
